<?php
namespace Swork\Server;

use Swork\Helper\ArrayHelper;
use Swork\Service;

/**
 * 连接fd处理器
 * Class Connection
 * @package Swork\Server
 */
class Connection
{
    /**
     * 获取已储存的连接
     * @return array|mixed
     */
    public static function getStoredList()
    {
        $list = [];
        $table = Service::$server->table;
        foreach ($table as $key => $item)
        {
            if (strpos($key, 'srv-fd') !== false)
            {
                $key = substr($key, 6);
                $list[$key] = ArrayHelper::toArray($item['data']);
            }
        }
        return $list;
    }

    /**
     * 获取储存指定的连接
     * @param int $fd 连接描述符
     * @return mixed
     */
    public static function get(int $fd)
    {
        $info = Service::$server->table->get("srv-fd$fd", 'data');
        if ($info != false)
        {
            return ArrayHelper::toArray($info);
        }
        return false;
    }

    /**
     * 更新连接
     * @param int $fd 连接描述符
     * @param array $exts 额外保存的内容
     */
    public static function update(int $fd, array $exts = [])
    {
        $info = Service::$server->table->get("srv-fd$fd");
        if ($info === false)
        {
            $info = [];
        }
        $info = json_decode($info['data'] ?? '[]', true);
        $info['time'] = microtime(true);
        foreach ($exts as $key => $value)
        {
            $info[$key] = $value;
        }
        Service::$server->table->set("srv-fd$fd", ['data' => json_encode($info)]);
    }

    /**
     * 清除连接
     * @param int $fd 连接描述符
     */
    public static function remove(int $fd)
    {
        Service::$server->table->del("srv-fd$fd");
    }
}
